package com.crawler58.entity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public abstract class Base implements Serializable {

	private static final long serialVersionUID = -6419829134275430292L;
	
	@Expose
	@SerializedName("url")
	private String url;

	@Expose
	@SerializedName("title")
	private String title;

	public Base() {}
	
	public Base(String title, String url) {
		this.title = title;
		this.url = url;
	}

	static String _cmd = "d:\\phantomjs\\phantomjs.exe --output-encoding=gbk --load-images=no --web-security=no ";
	
	/** 日志记录 */
	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	/** Json转换器 */
	protected final static Gson GSON = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

	/**
	 * 将对象转换为Json字符串
	 * @param obj
	 * @return
	 */
	protected String toJson(Object obj) {
		return GSON.toJson(obj);
	}

	/**
	 * 将Json字符串转换为对象
	 * @param json
	 * @return
	 */
	/*protected <T> T fromJson(String json) {
		Type type = new TypeToken<T>(){}.getType();
		return GSON.fromJson(json, type);
	}*/

	/*protected List<?> fromJson(String json) {
		Type clazz = getClass();
		Type type = new TypeToken<List<clazz()>>(){}.getType();
		return GSON.fromJson(json, type);
	}*/
	
	protected List<?> fromJson(String json, Class<?> clazz) {
		Type type = type(List.class, clazz);
		List<?> seeds = GSON.fromJson(json, type);
		return seeds;
	}
	
	protected ParameterizedType type(final Class<?> raw, final Type... args) {
        return new ParameterizedType() {
            public Type getRawType() {
                return raw;
            }
            public Type[] getActualTypeArguments() {
                return args;
            }
            public Type getOwnerType() {
                return null;
            }
        };
    }
	
	public abstract List<? extends Base> generateBase(String str);
	
	public List<? extends Base> fetchMe(String js) {
		String cmd = _cmd + " " + js + " " + this.url;
		System.out.println(cmd);
		String str = executeCmd(cmd);
		System.out.println(str);
		return generateBase(str);
	}

	public String executeCmd(String cmd) {
		Process proc = null;
		BufferedReader br = null;
		StringBuffer content = new StringBuffer();
		String line = "";
		try {
			proc = Runtime.getRuntime().exec(cmd);
			br = new BufferedReader(new InputStreamReader(proc.getInputStream(), "gbk"));
			while ((line = br.readLine()) != null) {
				content.append(line.trim()
						);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return content.toString();
	}

}
